/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.service.impl;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.vacoor.nothing.security.entity.Permission;
import org.vacoor.nothing.security.service.PermissionService;
import org.vacoor.nothing.security.shiro.filter.mgt.CustomFilterChainManager;
import org.vacoor.nothing.security.shiro.realm.ShiroDatabaseRealm;
import org.vacoor.nothing.web.service.support.CrudServiceImpl;

import java.util.List;

/**
 * @author vacoor
 */
@Service
public class PermissionServiceImpl extends CrudServiceImpl<Permission, String> implements PermissionService, InitializingBean, BeanNameAware, BeanFactoryAware {
    @Autowired
    CustomFilterChainManager chainManager;
    @Autowired
    ShiroDatabaseRealm realm;

    @Override
    public List<Permission> findPermissionsByRoleName(String roleName) {
        return findMany("roles.name", roleName);
    }

    // --------------------
    private BeanFactory beanFactory;
    private String beanName;

    @Override
    public void afterPropertiesSet() throws Exception {
        PermissionService permService = beanFactory.getBean(beanName, PermissionService.class);

        List<Permission> allPermissions = permService.findAll();

//        chainManager.setDynamicFilterChainDefinitionMap(null);
        chainManager.updateFilterChain();

        // 用户角色变化或角色全县变化, 这里不用
        // realm.getAuthenticationCache().clear();
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
